﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OrmSmackdown.LinqToSql
{
    public class Crud : ICrud
    {
        Linq2SqlDataContext _ctx;

        public Crud()
        {
            _ctx = new Linq2SqlDataContext();
        }

        public int Create(string firstName, string lastName, string email)
        {
            var newPerson = new Person() { FirstName = firstName, LastName = lastName, Email = email,UserType="CN" };
            _ctx.Persons.InsertOnSubmit(newPerson);
            _ctx.SubmitChanges();
            return newPerson.PersonId;
        }

        public IPerson Read(int id)
        {
            return _ctx.Persons.Where(p => p.PersonId == id).FirstOrDefault();
        }

        public void Update(int id, string firstName, string lastName, string email)
        {
            var person = _ctx.Persons.Where(p => p.PersonId == id).FirstOrDefault();
            person.FirstName = firstName;
            person.LastName = lastName;
            person.Email = email;

            _ctx.SubmitChanges();
        }

        public void Delete(int id)
        {
            var person = _ctx.Persons.Where(p => p.PersonId == id).FirstOrDefault();
            _ctx.Persons.DeleteOnSubmit(person);
            _ctx.SubmitChanges();            
        }

        public void Dispose()
        {
            _ctx.Dispose();
        }
    }
}
